/**
* ComplexAccordionButton class "wraps" an IComplexButton type (specifically to be used in OBO_Accordion
* and adds typical mouseevent handlers
* @author Devon O.
*/

package src.uipackage.ui.complexbuttons {
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import com.onebyonedesign.ui.complexbuttons.events.ComplexButtonEvent;

	public class ComplexAccordionButton extends Sprite {

		private var _selected:Boolean = false;
		
		private var _buttonInstance:*;
		
		public function ComplexAccordionButton(btn:IComplexButton) {
			if (btn.data == null) throw new Error("ComplexButton Error: button must have data property.");
			
			_buttonInstance = btn;
				
			_buttonInstance.addEventListener(Event.ADDED_TO_STAGE, init);
			_buttonInstance.addEventListener(Event.REMOVED_FROM_STAGE, kill);
			addChild(_buttonInstance);
		}
		
		public function get buttonInstance():* {
			return _buttonInstance;
		}
		
		private function init(event:Event = null):void {
			_buttonInstance.removeEventListener(Event.ADDED_TO_STAGE, init);
			
			addEvents();
		}
		
		private function onMouseRelease(event:MouseEvent):void {
			dispatch(ComplexButtonEvent.RELEASE);
			selected = true;
		}
		
		private function onOver(event:MouseEvent):void {
			if (!_selected) {
				_buttonInstance.displayOver();
				dispatch(ComplexButtonEvent.ROLL_OVER);
			}
		}
		
		private function onOut(event:MouseEvent):void {
			if (!_selected) {
				_buttonInstance.displayUp();
				dispatch(ComplexButtonEvent.ROLL_OUT);
			}
		}
		
		private function dispatch(type:String):void {
			dispatchEvent(new ComplexButtonEvent(type, _buttonInstance.data));
		}
		
		internal function reset():void {
			_selected = false;
			_buttonInstance.displayUp();
			addEvents();
		}
		
		private function removeEvents():void {
			_buttonInstance.hitArea.removeEventListener(MouseEvent.CLICK, onMouseRelease);
			_buttonInstance.hitArea.removeEventListener(MouseEvent.MOUSE_OVER, onOver);
			_buttonInstance.hitArea.removeEventListener(MouseEvent.MOUSE_OUT, onOut);

		}
		
		private function addEvents():void {
			if (!_selected) {
				_buttonInstance.hitArea.addEventListener(MouseEvent.CLICK, onMouseRelease);
				_buttonInstance.hitArea.addEventListener(MouseEvent.MOUSE_OVER, onOver);
				_buttonInstance.hitArea.addEventListener(MouseEvent.MOUSE_OUT, onOut);
			}
		}
		
		private function kill(event:Event):void {
			_buttonInstance.removeEventListener(Event.REMOVED_FROM_STAGE, kill);
			removeEvents();
			_buttonInstance = null;
		}
		
		internal function get data():String {
			return _buttonInstance.data;
		}
		internal function get selected():Boolean {
			return _selected;
		}
		internal function set selected(sel:Boolean):void {
			_selected = sel;
			_buttonInstance.displayDown();
			removeEvents();
		}
	}
}
